package no.ntnu.fp.messages.impl;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.MessageCode;
import no.ntnu.fp.model.Employee;
import no.ntnu.fp.model.Notice;
import no.ntnu.fp.utils.XmlParser;

public class NoticeAddedOrUpdatedMessage implements Message {
	private final Notice notice;
	private final Employee notifier;
	
	public NoticeAddedOrUpdatedMessage(Notice notice, Employee notifier) {
		this.notice = notice;
		this.notifier = notifier;
	}

	public NoticeAddedOrUpdatedMessage() {
		this(null, null);
	}

	public Notice getNotice() {
		return notice;
	}

	public Employee getNotifier() {
		return notifier;
	}

	@Override
	public MessageCode getMessageCode() {
		return MessageCode.NOTICE_ADDED_OR_UPDATED_MESSAGE;
	}

	@Override
	public Message fromXmlString(String xml) {
		Document doc = XmlParser.parseXmlString(xml);
		Notice notice = new Notice((Element)doc.getElementsByTagName("notice").item(0));
		Employee notifier = new Employee((Element)doc.getElementsByTagName("employee").item(0));
		return new NoticeAddedOrUpdatedMessage(notice, notifier);
	}

	@Override
	public String toString() {
		Document doc = XmlParser.getThreadLocalDocumentBuilder().newDocument();
		Element messageElement = doc.createElement("message");
		messageElement.appendChild(notice.toXml(doc));
		messageElement.appendChild(notifier.toXml(doc));
		return getMessageCode() + XmlParser.convertXmlToString(messageElement);
	}
}
